import { useState, useEffect, useRef } from 'react'
import { useNavigate, useSearchParams } from 'react-router-dom'
import { Image } from 'antd-mobile'
import { LeftOutline } from 'antd-mobile-icons'
import dataService, { type Training } from '../../services/dataService'

interface TrainingStep {
  id: number
  name: string
  duration: number // 秒
  image: string
  type: 'exercise' | 'rest'
}

const TrainingSession = () => {
  const navigate = useNavigate()
  const [searchParams] = useSearchParams()
  const trainingId = searchParams.get('id')
  
  const [training, setTraining] = useState<Training | null>(null)
  // 移除currentStepIndex，因为点击完成直接跳转
  const [timeLeft, setTimeLeft] = useState(22) // 当前动作剩余时间（秒）
  const [totalElapsedTime, setTotalElapsedTime] = useState(399) // 总计用时（秒），对应06:39
  const [isPlaying] = useState(true)
  const [isPaused, setIsPaused] = useState(false)
  const timerRef = useRef<NodeJS.Timeout | null>(null)

  // 训练步骤数据
  const trainingSteps: TrainingStep[] = [
    { id: 1, name: '紧致背部', duration: 30, image: '/紧致背部.png', type: 'exercise' },
    { id: 2, name: '休息', duration: 30, image: '', type: 'rest' },
    { id: 3, name: '平板支撑', duration: 30, image: '/平板支撑.png', type: 'exercise' },
    { id: 4, name: '休息', duration: 30, image: '', type: 'rest' },
    { id: 5, name: '四头肌腿部训练', duration: 45, image: '/四头肌腿部训练.png', type: 'exercise' },
    { id: 6, name: '休息', duration: 30, image: '', type: 'rest' },
    { id: 7, name: '箭步蹲跳', duration: 30, image: '/箭步蹲跳.png', type: 'exercise' },
    { id: 8, name: '休息', duration: 30, image: '', type: 'rest' },
    { id: 9, name: '深蹲跳跃', duration: 30, image: '/深蹲跳跃.png', type: 'exercise' },
    { id: 10, name: '休息', duration: 30, image: '', type: 'rest' },
    { id: 11, name: '跪姿股四头肌拉伸', duration: 30, image: '/跪姿股四头肌拉伸.png', type: 'exercise' },
    { id: 12, name: '体侧屈腔斜肌拉伸', duration: 30, image: '/体侧屈腔斜肌拉伸.png', type: 'exercise' }
  ]

  // 当前步骤为平板支撑（索引2）
  const currentStep = trainingSteps[2] // 平板支撑
  const nextExerciseStep = trainingSteps[4] // 四头肌腿部训练

  useEffect(() => {
    if (trainingId) {
      const trainingData = dataService.getTrainingById(parseInt(trainingId))
      if (trainingData) {
        setTraining(trainingData)
      }
    }
  }, [trainingId])

  // 计时器逻辑
  useEffect(() => {
    if (isPlaying && !isPaused && timeLeft > 0) {
      timerRef.current = setTimeout(() => {
        setTimeLeft(prev => prev - 1)
        setTotalElapsedTime(prev => prev + 1)
      }, 1000)
    }
    
    return () => {
      if (timerRef.current) {
        clearTimeout(timerRef.current)
      }
    }
  }, [isPlaying, isPaused, timeLeft])

  // 格式化时间显示
  const formatTime = (seconds: number) => {
    const mins = Math.floor(seconds / 60)
    const secs = seconds % 60
    return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  }

  // 暂停/恢复训练
  const handlePause = () => {
    setIsPaused(!isPaused)
  }

  // 完成当前动作，跳转到塑性训练页面
  const handleComplete = () => {
    // 点击完成按钮直接跳转到塑性训练页面
    navigate('/shape-training')
  }
  
  // const handlePlayPause = () => {
  //   setIsPlaying(!isPlaying)
  // }

  // const handleStop = () => {
  //   setIsPlaying(false)
  //   setTimeLeft(22)
  // }

  if (!training) {
    return (
      <div className="training-session">
        <div className="loading">加载中...</div>
      </div>
    )
  }

  // if (showFullScreen) {
  //   return (
  //     <div className="fullscreen-training">
  //       <div className="fullscreen-header">
  //         <span className="training-info">训练 5/12</span>
  //         <span className="time-display">06:39</span>
  //       </div>
  //       
  //       <div className="fullscreen-image">
  //         <Image
  //           src={training.cover}
  //           alt="平板支撑"
  //           width="100%"
  //           height="100%"
  //           fit="cover"
  //         />
  //       </div>
  //       
  //       <div className="fullscreen-footer">
  //         <div className="current-time">00:22</div>
  //         <div className="current-exercise">平板支撑</div>
  //       </div>
  //     </div>
  //   )
  // }
  
  return (
    <div className="training-session">
      {/* 顶部进度区域 */}
      <div className="training-header">
        <button className="back-btn" onClick={() => navigate(-1)}>
          <LeftOutline />
        </button>
        <div className="progress-info">
          <span className="training-progress">训练 5/12</span>
          <span className="total-time">{formatTime(totalElapsedTime)}</span>
        </div>
      </div>
      
      {/* 中间训练动作展示区域 */}
      <div className="training-display">
        <div className="action-image-container">
          <Image
            src={currentStep.image}
            alt={currentStep.name}
            width="100%"
            height="100%"
            fit="cover"
            style={{ borderRadius: '24px' }}
          />
        </div>
        
        <div className="action-info">
          <div className="remaining-time">{formatTime(timeLeft)}</div>
          <div className="action-name">{currentStep.name}</div>
        </div>
      </div>
      
      {/* 底部控制区域 */}
      <div className="control-section">
        <div className="next-training">
          <span className="next-label">下一个训练</span>
          <div className="next-info">
            <span className="next-name">{nextExerciseStep.name}</span>
            <span className="next-duration">{formatTime(nextExerciseStep.duration)}</span>
          </div>
        </div>
      
        <div className="control-buttons">
          <button className="pause-btn" onClick={handlePause}>
            {isPaused ? '继续' : '暂停'}
          </button>
          <button className="complete-btn" onClick={handleComplete}>
            完成
          </button>
        </div>
        </div>

      <style>{`
        .training-session {
          min-height: 100vh;
          background: #ffffff;
          display: flex;
          flex-direction: column;
        }
        
        /* 顶部进度区域 */
        .training-header {
          background: #ffffff;
          padding: 44px 20px 20px;
          display: flex;
          align-items: center;
          justify-content: space-between;
          box-shadow: 0 2px 8px rgba(0,0,0,0.04);
        }
        
        .back-btn {
          width: 36px;
          height: 36px;
          border-radius: 50%;
          background: #f8f9fa;
          border: none;
          display: flex;
          align-items: center;
          justify-content: center;
          cursor: pointer;
          font-size: 18px;
          color: #333333;
          transition: all 0.3s ease;
        }
        
        .back-btn:hover {
          background: #e9ecef;
          transform: scale(1.05);
        }
        
        .progress-info {
          display: flex;
          align-items: center;
          gap: 24px;
        }
        
        .training-progress {
          font-size: 18px;
          font-weight: 600;
          color: #333333;
        }
        
        .total-time {
          font-size: 18px;
          font-weight: 600;
          color: #666666;
        }
        
        /* 中间训练动作展示区域 */
        .training-display {
          flex: 1;
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
          padding: 40px 24px;
          background: #ffffff;
        }
        
        .action-image-container {
          width: 280px;
          height: 280px;
          border-radius: 24px;
          overflow: hidden;
          margin-bottom: 32px;
          box-shadow: 0 8px 32px rgba(0,0,0,0.12);
        }
        
        .action-info {
          text-align: center;
        }
        
        .remaining-time {
          font-size: 56px;
          font-weight: 700;
          color: #333333;
          margin-bottom: 8px;
          letter-spacing: -1px;
        }
        
        .action-name {
          font-size: 20px;
          font-weight: 600;
          color: #666666;
        }
        
        /* 底部控制区域 */
        .control-section {
          background: #ffffff;
          padding: 24px 20px 32px;
          border-radius: 24px 24px 0 0;
          box-shadow: 0 -4px 20px rgba(0,0,0,0.08);
        }
        
        .next-training {
          margin-bottom: 28px;
          padding: 16px 20px;
          background: #f8f9fa;
          border-radius: 16px;
        }
        
        .next-label {
          font-size: 14px;
          color: #999999;
          font-weight: 500;
          display: block;
          margin-bottom: 8px;
        }
        
        .next-info {
          display: flex;
          align-items: center;
          justify-content: space-between;
        }
        
        .next-name {
          font-size: 16px;
          font-weight: 600;
          color: #333333;
        }
        
        .next-duration {
          font-size: 14px;
          color: #666666;
          font-weight: 500;
        }
        
        .control-buttons {
          display: flex;
          gap: 16px;
        }
        
        .pause-btn, .complete-btn {
          flex: 1;
          height: 52px;
          border-radius: 26px;
          font-size: 16px;
          font-weight: 600;
          cursor: pointer;
          transition: all 0.3s ease;
          border: none;
        }
        
        .pause-btn {
          background: #ffffff;
          border: 2px solid #FF6B35;
          color: #FF6B35;
        }
        
        .pause-btn:hover {
          background: rgba(255, 107, 53, 0.05);
          transform: translateY(-1px);
          box-shadow: 0 4px 12px rgba(255, 107, 53, 0.2);
        }
        
        .complete-btn {
          background: #FF6B35;
          color: #ffffff;
          box-shadow: 0 4px 16px rgba(255, 107, 53, 0.3);
        }
        
        .complete-btn:hover {
          background: #E55A2B;
          transform: translateY(-1px);
          box-shadow: 0 6px 20px rgba(255, 107, 53, 0.4);
        }
        
        .pause-btn:active, .complete-btn:active {
          transform: scale(0.98);
        }
        
        .loading {
          display: flex;
          align-items: center;
          justify-content: center;
          height: 100vh;
          font-size: 16px;
          color: #666666;
          background: #ffffff;
        }
      `}</style>
    </div>
  )
}

export default TrainingSession
